package com.food.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.food.admin.dto.StoreRegisterDetailDto;
import com.food.admin.dto.StoreRegisterListDto;
import com.food.admin.entity.*;
import com.food.admin.exception.storeRegisterException.StoreRegisterException;
import com.food.admin.exception.storeRegisterException.StoreRegisterExceptionCode;
import com.food.admin.form.StoreRegisterListForm;
import com.food.admin.form.StoreRegisterRejectForm;
import com.food.admin.form.StoreRegisterIdForm;
import com.food.admin.mapper.StoreRegisterMapper;
import com.food.admin.model.ConstantData;
import com.food.admin.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.food.admin.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商家注册表 服务实现类
 * </p>
 *
 * @author 帅得一
 * @since 2023年06月13日
 */
@Service
public class StoreRegisterServiceImpl extends ServiceImpl<StoreRegisterMapper, StoreRegister> implements StoreRegisterService {
   @Autowired
   private RedisUtil redisUtil;
   @Autowired
   private AccountService accountService;
    @Autowired
    private StoreRegisterMapper storeRegisterMapper;
    @Autowired
    private StoreRegisterAttachmentService storeRegisterAttachmentService;
    @Autowired
    private StoreAttachmentService storeAttachmentService;
    @Autowired
    private StoreInfoService storeInfoService;
    @Autowired
    private MerchantAccountService merchantAccountService;
    @Autowired
    private MerchantAccountInfoService  merchantAccountInfoService;
    @Override
    public MyPage<StoreRegisterListDto> listByPageAndCondition(StoreRegisterListForm form) throws Exception {
        QueryWrapper<StoreRegister> storeRegisterQueryWrapper = new QueryWrapper<>();
        //条件查询
        if (form.getStateId()!=null){
            storeRegisterQueryWrapper.eq("store_register_status",form.getStateId());
        }
        if (form.getStartTime()!=null&&form.getStartTime()!=""){
            DateTime dateTime = DateUtils.parseStringToDateTime(form.getStartTime());
            storeRegisterQueryWrapper.ge("store_register_create_date",dateTime);
        }
        if (form.getEndTime()!=null&&form.getEndTime()!=""){
            DateTime dateTime = DateUtils.parseStringToDateTime(form.getEndTime());
            storeRegisterQueryWrapper.le("store_register_create_date",dateTime);
        }
        //分页
        Page<StoreRegister> storeRegisterPage = new Page<>(form.getPageIndex(),form.getPageSize());
        storeRegisterMapper.selectPage(storeRegisterPage, storeRegisterQueryWrapper);
        MyPage<StoreRegisterListDto> listDtoMyPage = new MyPage<>();
        listDtoMyPage.setPages(storeRegisterPage.getPages());
        listDtoMyPage.setPageIndex(storeRegisterPage.getCurrent());
        listDtoMyPage.setPageSize(storeRegisterPage.getSize());
        listDtoMyPage.setTotal(storeRegisterPage.getTotal());
        ArrayList<StoreRegisterListDto> storeRegisterListDtos = new ArrayList<>();
        for (StoreRegister record : storeRegisterPage.getRecords()) {
            StoreRegisterListDto dto = BeanUtil.toBean(record, StoreRegisterListDto.class);
            if (dto.getStoreRegisterStatus()==ConstantData.STORE_REGISTER_STATE_CHECK){
                dto.setState("待审核");
            }else if (dto.getStoreRegisterStatus()==ConstantData.STORE_REGISTER_STATE_PASS){
                dto.setState("审核通过");
            }else if (dto.getStoreRegisterStatus()==ConstantData.STORE_REGISTER_STATE_FAIL){
                dto.setState("审核不通过");
            }else if (dto.getStoreRegisterStatus()==ConstantData.STORE_REGISTER_STATE_CANCEL){
                dto.setState("取消审核");
            }
            storeRegisterListDtos.add(dto);
        }
        listDtoMyPage.setList(storeRegisterListDtos);
        return listDtoMyPage;
    }

    @Override
    public StoreRegisterDetailDto getDetail(StoreRegisterIdForm form) {
        StoreRegister storeRegister = getById(form.getStoreRegisterId());
        //前置业务处理
        if (storeRegister== null){
            throw new StoreRegisterException(StoreRegisterExceptionCode.STORE_REGISTER_IS_NOT_EXIST);
        }
        StoreRegisterDetailDto detailDto = BeanUtil.toBean(storeRegister, StoreRegisterDetailDto.class);
        //装配状态
        if (detailDto.getStoreRegisterStatus()==ConstantData.STORE_REGISTER_STATE_CHECK){
            detailDto.setStoreRegisterStatusName("待审核");
        }else if (detailDto.getStoreRegisterStatus()==ConstantData.STORE_REGISTER_STATE_PASS){
            detailDto.setStoreRegisterStatusName("审核通过");
        }else if (detailDto.getStoreRegisterStatus()==ConstantData.STORE_REGISTER_STATE_FAIL){
            detailDto.setStoreRegisterStatusName("审核不通过");
        }else if (detailDto.getStoreRegisterStatus()==ConstantData.STORE_REGISTER_STATE_CANCEL){
            detailDto.setStoreRegisterStatusName("取消审核");
        }
        //装配附件
        ArrayList<String> attachment = new ArrayList<>();
        QueryWrapper<StoreRegisterAttachment> storeRegisterAttachmentQueryWrapper = new QueryWrapper<>();
        storeRegisterAttachmentQueryWrapper.eq("store_register_id",form.getStoreRegisterId());
        List<StoreRegisterAttachment> attachments = storeRegisterAttachmentService.list(storeRegisterAttachmentQueryWrapper);
        for (StoreRegisterAttachment storeRegisterAttachment : attachments) {
            attachment.add(storeRegisterAttachment.getStoreRegisterAttachmentFilePath());
        }
        detailDto.setAttachment(attachment);
        return detailDto;
    }

    @Override
    @Transactional
    public void rejectRegister(StoreRegisterRejectForm form) throws Exception {
        StoreRegister storeRegister = getById(form.getStoreRegisterId());
        //前置业务处理
        if (storeRegister== null){
            throw new StoreRegisterException(StoreRegisterExceptionCode.STORE_REGISTER_IS_NOT_EXIST);
        }
        //不为审核状态
        if (storeRegister.getStoreRegisterStatus()!= ConstantData.STORE_REGISTER_STATE_CHECK){
            throw new StoreRegisterException(StoreRegisterExceptionCode.STORE_REGISTER_STATE_NOT_CHECK);
        }
        //更新注册表
        storeRegister.setStoreRegisterRejectReason(form.getStoreRegisterRejectReason());
        storeRegister.setStoreRegisterStatus(ConstantData.STORE_REGISTER_STATE_FAIL);
        //更新人 和时间 为当前操作管理员
        String accessToken = WebUtil.getRequest().getHeader("accessToken");
        String refreshToken = redisUtil.get(accessToken);
        Integer userId = JwtUtil.getUserId(refreshToken);
        Account byId = accountService.getById(userId);
        storeRegister.setStoreRegisterUpdateUser(byId.getAccountNickName());
        storeRegister.setStoreRegisterUpdateDate(DateUtils.parseString(LocalDateTime.now(),"yyyy-MM-dd HH:mm:ss"));
        updateById(storeRegister);
    }

    @Override
    @Transactional
    public void passRegister(StoreRegisterIdForm form) throws Exception {
        StoreRegister storeRegister = getById(form.getStoreRegisterId());
        //前置业务处理
        if (storeRegister== null){
            throw new StoreRegisterException(StoreRegisterExceptionCode.STORE_REGISTER_IS_NOT_EXIST);
        }
        //不为审核状态
        if (storeRegister.getStoreRegisterStatus()!= ConstantData.STORE_REGISTER_STATE_CHECK){
            throw new StoreRegisterException(StoreRegisterExceptionCode.STORE_REGISTER_STATE_NOT_CHECK);
        }
        //更新注册表状态
        storeRegister.setStoreRegisterStatus(ConstantData.STORE_REGISTER_STATE_PASS);
        //更新人 和时间 为当前操作管理员
        String accessToken = WebUtil.getRequest().getHeader("accessToken");
        String refreshToken = redisUtil.get(accessToken);
        Integer userId = JwtUtil.getUserId(refreshToken);
        Account byId = accountService.getById(userId);
        storeRegister.setStoreRegisterUpdateUser(byId.getAccountNickName());
        storeRegister.setStoreRegisterUpdateDate(DateUtils.parseString(LocalDateTime.now(),"yyyy-MM-dd HH:mm:ss"));
        updateById(storeRegister);

        //生成商铺基本信息
        StoreInfo storeInfo = new StoreInfo();
        storeInfo.setStoreInfoName(storeRegister.getStoreRegisterStoreName());
        //绑定用户Id 根据手机号查询商家账号信息表
        MerchantAccount merchantAccount = merchantAccountService.getOne(
                new QueryWrapper<MerchantAccount>().eq("merchant_phone",storeRegister.getStoreRegisterPhone()));
        storeInfo.setStoreInfoUserAccount(merchantAccount.getMerchantId()+"");
        storeInfo.setStoreInfoAddress(storeRegister.getStoreRegisterAddress());
        storeInfo.setStoreInfoLinkMan(storeRegister.getStoreRegisterLinkMan());
        storeInfo.setStoreInfoPhone(storeRegister.getStoreRegisterPhone());
        storeInfo.setStoreInfoLicense(storeRegister.getStoreRegisterLicense());
        storeInfo.setStoreInfoPermit(storeRegister.getStoreRegisterPermit());
        storeInfo.setStoreInfoStatus(ConstantData.STORE_STATE_NORMAL);
        storeInfo.setStoreInfoStoreStatus(ConstantData.STORE_BUSY_STATE_DISABLE);
        //查询商家用户信息
        MerchantAccountInfo merchantAccountInfo = merchantAccountInfoService.getOne(
                new QueryWrapper<MerchantAccountInfo>().eq("merchant_id",merchantAccount.getMerchantId()));
        storeInfo.setStoreInfoCreateUser(merchantAccountInfo.getMerchantInfoRealName());
        storeInfo.setStoreInfoCreateDate(DateUtils.parseString(LocalDateTime.now(),"yyyy-MM-dd HH:mm:ss"));
        storeInfoService.save(storeInfo);
        //更新同步商铺附件表
        ArrayList<StoreAttachment> storeAttachments = new ArrayList<>();
        QueryWrapper<StoreRegisterAttachment> storeRegisterAttachmentQueryWrapper = new QueryWrapper<>();
        storeRegisterAttachmentQueryWrapper.eq("store_register_id",form.getStoreRegisterId());
        List<StoreRegisterAttachment> registerAttachments = storeRegisterAttachmentService.list(storeRegisterAttachmentQueryWrapper);
        for (StoreRegisterAttachment registerAttachment : registerAttachments) {
            StoreAttachment storeAttachment = new StoreAttachment();
            storeAttachment.setStoreAttachmentStoreId(storeInfo.getStoreInfoId());
            storeAttachment.setStoreAttachmentNewFile(registerAttachment.getStoreRegisterAttachmentFile());
            storeAttachment.setStoreAttachmentSize(registerAttachment.getStoreRegisterAttachmentSize());
            storeAttachment.setStoreAttachmentFilePath(registerAttachment.getStoreRegisterAttachmentFilePath());
            storeAttachment.setStoreAttachmentFileSuffix(registerAttachment.getStoreRegisterAttachmentFileSuffix());
            storeAttachment.setStoreAttachmentCreateDate(registerAttachment.getStoreRegisterAttachmentCreateDate());
            storeAttachments.add(storeAttachment);
        }
        storeAttachmentService.saveBatch(storeAttachments);

    }
}
